import Vue from 'vue'
import { loginApi } from "@/api/api"
import { ACCESS_TOKEN } from "@/store/mutation-types"
import { router } from "@/router"




const user = {
  state: {
    isLogin: false,
    token: ''
  },

  mutations: {
    SET_ISLOGIN: (state, isLogin) => {
      state.isLogin = isLogin
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
  },

  actions: {
    // 登录
    async Login({ commit }, loginInfo) {
      let data = await loginApi(loginInfo);
      commit('SET_ISLOGIN', true);
      commit('SET_TOKEN', data)
      Vue.ls.set(ACCESS_TOKEN, data, 7 * 24 * 60 * 60 * 1000)
    },
    // 模拟登录
    async LoginMock({ commit }, loginInfo) {
      alert('登录成功，现在跳转到首页');
      commit('SET_ISLOGIN', true);
      commit('SET_TOKEN', 'token123456')
      Vue.ls.set(ACCESS_TOKEN, 'token123789', 7 * 24 * 60 * 60 * 1000)
      router.replace({ path: "/home" })
    },

    // 前端登出
    LogOutFront({ commit }) {
      return new Promise((resolve) => {
        commit('SET_TOKEN', '')
        commit('SET_ISLOGIN', false);
        Vue.ls.remove(ACCESS_TOKEN);
        resolve()
      })
    }
  }
}

export default user